package com.kohburg.baseplate.xdelay.service;

import com.kohburg.baseplate.xdelay.constant.XdelayConstant;
import com.kohburg.baseplate.xdelay.factory.RabbitTemplateFactory;
import com.kohburg.baseplate.xdelay.store.FlashStore;
import com.kohburg.baseplate.xdelay.util.MessageSeqUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 消息发送服务类
 *
 * @author : zenos hua
 * @date : 2020/6/17 19:51
 **/
@Service
public class MessageServiceImpl implements MessageService{

    @Autowired
    private RabbitTemplateFactory rabbitTemplateFactory;

    /**
     * 发送消息
     *
     * @param exchange 交换机
     * @param route 路由key
     * @param message 消息体
     */
    @Override
    public void send(String exchange, String route, Object message) {
        // 获取消息发送模板
        RabbitTemplate rabbitTemplate = rabbitTemplateFactory.getInstace();

        CorrelationData correlationData = new CorrelationData(MessageSeqUtil.createMessageSeq(XdelayConstant.ORIGN));

        // 发送延迟消息
        if (route == null) {
            rabbitTemplate.convertAndSend(exchange, message, correlationData);
        } else {
            rabbitTemplate.convertAndSend(exchange, route, message, correlationData);
        }

        // 放入内存
        FlashStore.message.put(correlationData.getId(), message);
    }
}
